package com.wolfpire.workflow.dao.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.stereotype.Repository;
import org.springframework.util.FileCopyUtils;

import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;
import com.wolfpire.workflow.dao.JbpmDao;

@Repository("jbpmDaoImpl")
public class JbpmDaoImpl extends BaseHibernateDao<Object, Long> implements JbpmDao {

	@Resource
	private JdbcTemplate jdbcTemplate;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String getDefXmlByDeployId(String deployId){
		
		String sql = "select * from JBPM4_LOB where  DEPLOYMENT_= ? ";
		/*Query query = getSession().createSQLQuery(sql);
		//query.setParameter(0, "process.jpdl.xml");
		query.setParameter(0, deployId);
		return  query.uniqueResult().toString();*/
		
		final DefaultLobHandler defaultLobHandler = new DefaultLobHandler();
		final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		String defxml = null;
		try {
			//this.jdbcTemplate.query(sql, new Object[]{"process.jpdl.xml",deployId}, new AbstractLobStreamingResultSetExtractor( ){
			this.jdbcTemplate.query(sql, new Object[]{deployId}, new AbstractLobStreamingResultSetExtractor( ){
				protected void streamData(ResultSet pset) throws SQLException,
						IOException {
					FileCopyUtils.copy(defaultLobHandler.getBlobAsBinaryStream(pset, "BLOB_VALUE_"), byteArrayOutputStream);
				}
			});
			
			defxml = new String(byteArrayOutputStream.toByteArray(),"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return defxml;
	}
	
}
